<template>
  <Layout>
    <div class="notification-management max-width-1500">
      <div class="header">
        <h2>通知管理</h2>
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索通知标题或内容"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchNotificationList"
            @keydown.enter="fetchNotificationList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchNotificationList" />
            </template>
          </el-input>
          <el-button type="primary" @click="handleCreateNotification">新增通知</el-button>
          <el-button type="success" @click="fetchNotificationList" :loading="loading">刷新</el-button>
          <el-button
              type="warning"
              @click="handleBatchSend"
              :disabled="selectedNotifications.length === 0"
          >
            批量发送({{ selectedNotifications.length }})
          </el-button>
          <el-button
              type="info"
              @click="handleBatchSetUnsent"
              :disabled="selectedNotifications.length === 0"
          >
            批量撤回({{ selectedNotifications.length }})
          </el-button>
          <el-button
              type="info"
              @click="handleBatchResetReadStatus"
              :disabled="selectedNotifications.length === 0"
          >
            重置已读({{ selectedNotifications.length }})
          </el-button>
          <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedNotifications.length === 0"
          >
            批量删除({{ selectedNotifications.length }})
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="notificationList"
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="notification_id" label="通知ID" width="100" sortable />
          <el-table-column prop="title" label="标题" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" show-overflow-tooltip>
            <template #default="scope">
              <span class="content-preview">{{ scope.row.content }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100">
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.type)">{{ getTypeLabel(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sender" label="发送者" width="120" >
            <template #default="scope">
             {{scope.row.sender?.name}}
            </template>
          </el-table-column>
          <el-table-column prop="is_sent" label="发送状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.is_sent ? 'success' : 'info'">
                {{ scope.row.is_sent ? '已发送' : '未发送' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                type="primary"
                @click="handleEditNotification(scope.row)"
                :disabled="scope.row.is_sent"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="primary"
                @click="handleSendNotification(scope.row)"
                :loading="sendingNotificationId === scope.row.notification_id"
                :disabled="scope.row.is_sent"
              >
                发送
              </el-button>
              <el-button 
                size="small" 
                type="info"
                @click="handleResetReadStatus(scope.row)"
                :disabled="!canResetReadStatus(scope.row)"
              >
                重置已读
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDeleteNotification(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[50, 500, 1000]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 新增/编辑通知弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="editingNotification ? '编辑通知' : '新增通知'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入通知标题" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input 
              v-model="form.content" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入通知内容" 
            />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择通知类型">
              <el-option label="信息" value="info" />
              <el-option label="成功" value="success" />
              <el-option label="警告" value="warning" />
              <el-option label="错误" value="error" />
            </el-select>
          </el-form-item>
          <el-form-item label="接收用户">
            <UserSelector 
              v-model="form.receive_user_ids" 
              :key="userSelectorKey"
            />
            <div class="tip">提示：不选择用户将向所有用户发送通知</div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Layout from '@/components/Layout.vue'
import UserSelector from '@/components/UserSelector.vue'
import { useSystemNotificationStore } from '@/stores/systemNotification'
import type { SystemNotification } from '@/api/modules/notification'
import { 
  getNotificationList, 
  createNotification, 
  editNotification,
  sendNotification,
  batchSendNotifications,
  batchSetUnsent,
  deleteNotification,
  batchDeleteNotifications,
  resetNotificationReadStatus,
  batchResetNotificationReadStatus
} from '@/api/modules/notification'
import { getUserList } from '@/api/modules/user'
import websocket, { WsRequestType } from '@/utils/websocket'

const systemNotificationStore = useSystemNotificationStore()

// 通知列表
const notificationList = ref<SystemNotification[]>([])

// 加载状态
const loading = ref(false)

// 删除通知时的加载状态
const deletingNotificationId = ref<number | null>(null)

// 发送通知时的加载状态
const sendingNotificationId = ref<number | null>(null)

// 提交表单时的加载状态
const submitLoading = ref(false)

// 表单引用
const formRef = ref()

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)

// 当前正在编辑的通知
const editingNotification = ref<SystemNotification | null>(null)

// 选中的通知
const selectedNotifications = ref<SystemNotification[]>([])

// 用户选择器的key，用于强制刷新
const userSelectorKey = ref(0)

// 所有用户ID列表
const allUserIds = ref<number[]>([])

// 表单数据
const form = reactive({
  title: '',
  content: '',
  type: 'info',
  receive_user_ids: [] as number[]
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择通知类型', trigger: 'change' }]
}

// 获取标签类型
const getTagType = (type: string) => {
  switch (type) {
    case 'success':
      return 'success'
    case 'warning':
      return 'warning'
    case 'error':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取类型标签文本
const getTypeLabel = (type: string) => {
  switch (type) {
    case 'success':
      return '成功'
    case 'warning':
      return '警告'
    case 'error':
      return '错误'
    default:
      return '信息'
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 判断是否可以重置已读状态
const canResetReadStatus = (notification: SystemNotification) => {
  // 只有已发送的通知才能重置已读状态
  if (!notification.is_sent) {
    return false;
  }
  
  // 如果是广播通知（receive_users 为 null），可以重置
  if (notification.receive_users === null) {
    return true;
  }
  
  // 如果是指定用户的通知，检查是否有用户已读
  if (notification.receive_users) {
    for (const userId in notification.receive_users) {
      if (notification.receive_users[userId].read) {
        return true;
      }
    }
  }
  
  // 默认不可重置
  return false;
};

// 表格行样式
const tableRowClassName = ({ row }: { row: any }) => {
  return systemNotificationStore.isNotificationRead(row) ? '' : 'unread-notification-row'
}

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchNotificationList();
};

// 获取所有用户列表
const fetchAllUsers = async () => {
  try {
    const response = await getUserList()
    allUserIds.value = response.data?.map(user => user.user_id!) || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取通知列表
const fetchNotificationList = async () => {
  loading.value = true
  try {
    const response = await getNotificationList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    notificationList.value = response.data?.list || []
    pagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    console.error('获取通知列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchNotificationList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchNotificationList()
}

// 处理新增通知
const handleCreateNotification = () => {
  // 重置表单
  Object.assign(form, {
    title: '',
    content: '',
    type: 'info',
    receive_user_ids: []
  })
  editingNotification.value = null
  // 强制刷新用户选择器
  userSelectorKey.value++
  dialogVisible.value = true
}

// 处理编辑通知
const handleEditNotification = (notification: SystemNotification) => {
  // 填充表单数据
  Object.assign(form, {
    title: notification.title,
    content: notification.content,
    type: notification.type,
    receive_user_ids: notification.receive_users 
      ? Object.keys(notification.receive_users).map(id => parseInt(id)) 
      : []
  })
  editingNotification.value = notification
  // 强制刷新用户选择器
  userSelectorKey.value++
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      // 处理接收用户ID
      let receiveUserIds = null;
      if (form.receive_user_ids && form.receive_user_ids.length > 0) {
        // 如果选择了用户，则使用选择的用户
        receiveUserIds = form.receive_user_ids;
      } else {
        // 如果未选择用户，则使用所有用户
        receiveUserIds = allUserIds.value;
      }
      
      if (editingNotification.value) {
        // 编辑通知
        await editNotification({
          notification_id: editingNotification.value.notification_id,
          title: form.title,
          content: form.content,
          type: form.type,
          receive_user_ids: receiveUserIds
        })
        ElMessage.success('通知编辑成功')
      } else {
        // 创建通知
        await createNotification({
          title: form.title,
          content: form.content,
          type: form.type,
          receive_user_ids: receiveUserIds
        })
        ElMessage.success('通知创建成功')
      }
      dialogVisible.value = false
      // 重新获取通知列表
      await fetchNotificationList()
    } catch (error) {
      console.error('保存通知失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 处理发送通知
const handleSendNotification = async (notification: SystemNotification) => {
  // 判断是否选择了特定用户
  const hasSpecificReceivers = notification.receive_users && 
    Object.keys(notification.receive_users).length > 0;
  
  const receiverText = hasSpecificReceivers 
    ? `指定的${Object.keys(notification.receive_users).length}位用户` 
    : '所有用户';
  
  ElMessageBox.confirm(
    `确定要发送通知 "${notification.title}" 给${receiverText}吗？`,
    '确认发送',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!notification.notification_id) return
    
    sendingNotificationId.value = notification.notification_id
    try {
      await sendNotification(notification.notification_id)
      ElMessage.success('通知发送成功')
      // 重新获取通知列表
      await fetchNotificationList()
    } catch (error) {
      console.error('发送通知失败:', error)
    } finally {
      sendingNotificationId.value = null
    }
  })
  .catch(() => {
    // 用户取消发送
  })
}

// 处理批量发送通知
const handleBatchSend = async () => {
  // 检查选中的通知中是否有指定了接收用户
  const hasSpecificReceivers = selectedNotifications.value.some(notification => 
    notification.receive_users && Object.keys(notification.receive_users).length > 0
  );
  
  const receiverText = hasSpecificReceivers 
    ? '（部分通知将发送给指定用户）' 
    : '';
  
  ElMessageBox.confirm(
    `确定要发送选中的 ${selectedNotifications.value.length} 条通知吗？${receiverText}`,
    '确认发送',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const notificationIds = selectedNotifications.value.map(n => n.notification_id).filter(id => id !== undefined);
      if (notificationIds.length === 0) {
        ElMessage.warning('请选择有效的通知进行发送');
        return;
      }
      
      await batchSendNotifications(notificationIds);
      ElMessage.success(`成功发送${notificationIds.length}条通知`);
      // 清空选中项
      selectedNotifications.value = [];
      // 重新获取通知列表
      await fetchNotificationList();
    } catch (error) {
      console.error('批量发送通知失败:', error);
    }
  })
  .catch(() => {
    // 用户取消发送
  })
}

// 处理批量设置为未发送状态
const handleBatchSetUnsent = async () => {
  ElMessageBox.confirm(
    `确定要撤回选中的 ${selectedNotifications.value.length} 条已发送通知吗？撤回后可以重新编辑和发送。`,
    '确认撤回',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const notificationIds = selectedNotifications.value
        .filter(n => n.is_sent) // 只选择已发送的通知
        .map(n => n.notification_id)
        .filter(id => id !== undefined);
        
      if (notificationIds.length === 0) {
        ElMessage.warning('请选择已发送的通知进行撤回');
        return;
      }
      
      await batchSetUnsent(notificationIds);
      ElMessage.success(`成功撤回${notificationIds.length}条通知`);
      // 清空选中项
      selectedNotifications.value = [];
      // 重新获取通知列表
      await fetchNotificationList();
    } catch (error) {
      console.error('批量撤回通知失败:', error);
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}

// 处理批量重置已读状态
const handleBatchResetReadStatus = async () => {
  ElMessageBox.confirm(
    `确定要重置选中的 ${selectedNotifications.value.length} 条通知的已读状态吗？重置后所有用户都需要重新查看。`,
    '确认重置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 过滤出可以重置已读状态的通知
      const resettableNotifications = selectedNotifications.value
        .filter(n => canResetReadStatus(n));
        
      const notificationIds = resettableNotifications
        .map(n => n.notification_id)
        .filter(id => id !== undefined);
        
      if (notificationIds.length === 0) {
        ElMessage.warning('请选择可以重置已读状态的通知');
        return;
      }
      
      await batchResetNotificationReadStatus(notificationIds);
      ElMessage.success(`成功重置${notificationIds.length}条通知的已读状态`);
      // 清空选中项
      selectedNotifications.value = [];
      // 重新获取通知列表
      await fetchNotificationList();
    } catch (error) {
      console.error('批量重置已读状态失败:', error);
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}

// 处理批量重置已读状态
const handleResetReadStatus = async (notification: SystemNotification) => {
  ElMessageBox.confirm(
    `确定要重置通知 "${notification.title}" 的已读状态吗？重置后所有用户都需要重新查看。`,
    '确认重置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!notification.notification_id) return;
    
    try {
      await resetNotificationReadStatus(notification.notification_id);
      ElMessage.success('已重置已读状态');
      // 重新获取通知列表
      await fetchNotificationList();
    } catch (error) {
      console.error('重置已读状态失败:', error);
    }
  })
  .catch(() => {
    // 用户取消操作
  })
};

// 处理选择变化
const handleSelectionChange = (val: SystemNotification[]) => {
  selectedNotifications.value = val
}

// 处理删除通知
const handleDeleteNotification = async (notification: SystemNotification) => {
  ElMessageBox.confirm(
    `确定要删除通知 "${notification.title}" 吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!notification.notification_id) return
    
    deletingNotificationId.value = notification.notification_id
    try {
      await deleteNotification(notification.notification_id)
      ElMessage.success('删除成功')
      // 重新获取通知列表
      await fetchNotificationList()
    } catch (error) {
      console.error('删除通知失败:', error)
    } finally {
      deletingNotificationId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除通知
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedNotifications.value.length} 条通知吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      const notificationIds = selectedNotifications.value.map(n => n.notification_id).filter(id => id !== undefined);
      if (notificationIds.length === 0) {
        ElMessage.warning('请选择有效的通知进行删除');
        return;
      }
      
      await batchDeleteNotifications(notificationIds);
      ElMessage.success(`成功删除${notificationIds.length}条通知`);
      // 清空选中项
      selectedNotifications.value = [];
      // 重新获取通知列表
      await fetchNotificationList();
    } catch (error) {
      console.error('批量删除通知失败:', error);
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 标记为已读
const markAsRead = (notification: any) => {
  if (!notification || !notification.notification_id) return
  
  // 发送WebSocket消息标记为已读
  const message = {
    type: WsRequestType.SYSTEM_NOTIFICATION_READ,
    notification_id: notification.notification_id
  }
  websocket.sendMessage(message)
  
  ElMessage.success('已标记为已读')
}

// 组件挂载时获取通知列表和所有用户列表
onMounted(() => {
  fetchNotificationList()
  fetchAllUsers()
})
</script>

<style scoped>
.notification-management {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: auto;
}

.content-preview {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.pagination-container {
  padding: 15px 0;
  display: flex;
  justify-content: flex-end;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.unread-notification-row {
  font-weight: bold;
}
</style>